package com.example.springboot.controller;

import com.example.springboot.common.result.Result;
import com.example.springboot.common.request.SetNewPasswordRequest;
import com.example.springboot.common.utils.VerCodeGenerateUtil;
import com.example.springboot.entity.ToEmail;
import com.example.springboot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.example.springboot.common.exception.ExceptionConstant.Captcha_ERROR;

@RestController
@RequestMapping("/email")
public class EmailController {
    // 目前的邮箱验证码
    private static String currentVerCode = "";

    // 引进邮件接口
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private AdminService adminService;

    // 获得发件人信息
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮箱验证码
     * @param toEmail
     * @return
     */
    @RequestMapping("sendEmail")
    public Result commonEmail(ToEmail toEmail) {

        // 获取随机验证码
        String verCode = VerCodeGenerateUtil.generateVerCode();

        currentVerCode = verCode;

        // 创建邮件信息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(toEmail.getTos());
        message.setSubject("验证码:" + verCode);

        message.setText("广金图书管理平台:\n" +
                "　　尊敬的用户,您好!\n"
                + "由于密码修改请求的邮件验证码为:" + verCode + ",本验证码 2 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n　　如非本人操作，请忽略该邮件。\n　　(这是一封通过自动发送的邮件，请不要直接回复）");

        mailSender.send(message);

        return Result.success();
    }

    /**
     * 重置新密码
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/setNewPassword")
    public Result setNewPassword(@RequestBody SetNewPasswordRequest request) throws Exception {
        String emailCode = request.getCode();
        if(!currentVerCode.equalsIgnoreCase(emailCode)) {
            throw new Exception(Captcha_ERROR);
        }
        adminService.setPasswordByUsername(request);
        return Result.success();
    }

}
